
using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(MeshCollider))]
[RequireComponent(typeof(Outline))]
public class Toy : MonoBehaviour
{
    private Rigidbody rb;
    private MeshCollider mc;

    private Outline outline;

    private string _toyName;

    private Vector3 originScale;

    private bool isMoving = false;

    private int _slotIndex = -1;

    public int SlotIndex
    {
        get
        {
            return _slotIndex;
        }
        set
        {
            _slotIndex = value;
        }
    }

    private bool _tagClear;

    public bool TagClear
    {
        get
        {
            return _tagClear;
        }
        set
        {
            _tagClear = value;
        }
    }

    public string ToyName
    {
        get
        {
            return _toyName;
        }
        set
        {
            _toyName = value;
        }
    }

    /// <summary>
    /// 是否进入槽子
    /// </summary>
    private bool isInSlot = false;

    public bool IsInSlot
    {
        get
        {
            return isInSlot;
        }
        private set
        {
            isInSlot = value;
        }
    }

    private void Awake()
    {
        outline = GetComponent<Outline>();
        if(outline != null) {
            outline.OutlineWidth = 6f;
        }
        MeshCollider collider = GetComponent<MeshCollider>();
        collider.convex = true;
        mc = collider;
        rb = GetComponent<Rigidbody>();
        originScale = transform.localScale;
    }

    private void OnEnable()
    {
        if (outline != null)
        {
            outline.enabled = false;
        }
        EventManager.Instance.Sub("hit", OnHitted);
        EventManager.Instance.Sub("unhit", OnUnHitted);
    }

    private void OnHitted(object data)
    {
        MeshCollider collider = (MeshCollider)data;
        MeshCollider mc = GetComponent<MeshCollider>();
        if (outline != null && mc == collider)
        {
            if(isMoving) {
                Debug.Log("！！！！！同一个物体不能重复加进去");
                return;
            }
            isMoving = true;
            GameManager.Instance().audioManager.PlayAudio(EAudioType.CLICK);

            outline.enabled = true;
            MoveToyToTargetSlot();

        }
        else
        {
            if(outline != null)
                outline.enabled = false;
        }

        // 前往目的地
        // transform.DOMove()
    }

    public void MoveToyToTargetSlot()
    {

        SlotManager slotManager = GameManager.Instance().slotManagers;
        int addIndex = slotManager.AddToSlots(transform);
        if (addIndex < 0)
        {
            Debug.Log("没有找到插入位置");
            return;
        }
        Debug.Log("插入的位置是：" + addIndex);

        Vector3 targetPos = slotManager.SlotTargetWorldPosByIndex(addIndex);
        rb.isKinematic = true;

        targetPos.y = 20;
        SlotIndex = addIndex;

        // transform.SetPositionAndRotation(new Vector3(transform.position.x,80,transform.position.z),Quaternion.identity);
        

        List<float> rotationArr = GameManager.Instance().game.posMap.GetValueOrDefault(ToyName);
        if (rotationArr != null && rotationArr.Count > 0)
        {
            Vector3 targetRotate = Vector3.zero;

            if (rotationArr.Count > 0)
            {
                targetRotate = new Vector3(rotationArr[0], rotationArr[1], rotationArr[2]);
            }
            // 旋转到目标欧拉角
            transform.DORotate(targetRotate, GameConsts.scaleAnimTime, RotateMode.Fast);
        }

        float scale = 0.8f;
        Vector3 targetScale = new Vector3(originScale.x * scale, originScale.y * scale, originScale.z * scale);
        transform.DOScale(targetScale, GameConsts.scaleAnimTime);
        transform.DOMove(targetPos, GameConsts.moveAnimTime).OnComplete(() =>
        {
            MoveComplete(targetPos);
        });
    }

    public void MoveComplete(Vector3 data)
    {
        // 为了在移动完毕之后才会触发结果
        GameManager.Instance().game.SubToy(transform);
        transform.position = data;
        IsInSlot = true;

        // 检查是否可以消除
        bool canClear = GameManager.Instance().slotManagers.CheckCanClear();
        if (canClear)
        {
            // 播放消除效果
            Debug.Log("可以消除");
        }
        else
        {
            Debug.LogWarning($"检查游戏是否结束");
            GameManager.Instance().slotManagers.CheckGameOver();
        }
        
    }

    public void StartClearAction()
    {
        StartCoroutine(ClearAction());
    }

    /// <summary>
    /// 消除的时候移动到消除中心去
    /// </summary>
    /// <returns></returns>
    public IEnumerator MoveToClearCenter(float x)
    {
        if(transform == null) {
            Debug.Log($"MoveToClearCenter trasform {transform.name}为空");
            yield return null;
        }
        Tween t = transform.DOMoveX(x, GameConsts.clearTime);
        yield return t.WaitForCompletion();
    }

    public IEnumerator ClearAction()
    {
        if(transform == null) {
            Debug.Log($"ClearAction trasform {transform.name}为空");
            yield return null;
        }
        // 满足消除条件后，两边的物体向中间的物体靠近来消除
        Tween t = transform.DOScale(Vector3.zero, GameConsts.clearTime);
        yield return t.WaitForCompletion();
        Destroy(gameObject);
    }

    public void EnableOutline(bool tag)
    {
        if(outline != null)
            outline.enabled = tag;
    }

    private void OnUnHitted(object data)
    {
        if (outline != null)
        {
            outline.enabled = false;
        }
    }

    private void OnDisable()
    {
        EventManager.Instance.UnSub("hit", OnHitted);
        EventManager.Instance.UnSub("unhit", OnUnHitted);
    }
}
